from image_utils import logging # 从image_utils.py中导入logging对象


def crop_image(image, crop_region):
    """
    裁剪图像
    :param image: 输入图像，numpy数组
    :param crop_region: 裁剪区域,格式为(上,下,左,右)
    :return: 裁剪后的图像
    """
    try:
        logging.info(f"开始裁剪图像，裁剪区域: {crop_region}")
        
        # 验证输入参数
        if image is None:
            raise ValueError("输入图像不能为空")
            
        if len(crop_region) != 4:
            raise ValueError("裁剪区域必须包含4个值(上,下,左,右)")
            
        top, bottom, left, right = crop_region
        
        # 验证裁剪区域是否有效
        height, width = image.shape[:2]
        if top < 0 or bottom > height or left < 0 or right > width:
            raise ValueError(f"裁剪区域超出图像范围(图像尺寸:{height}x{width})")
            
        if top >= bottom or left >= right:
            raise ValueError("裁剪区域无效(上必须小于下，左必须小于右)")
            
        # 执行裁剪
        cropped_image = image[top:bottom, left:right]
        
        # 记录裁剪结果信息
        logging.info(f"裁剪成功，结果尺寸: {cropped_image.shape}")
        return cropped_image
        
    except Exception as e:
        logging.error(f"裁剪图像时发生错误: {e}", exc_info=True)
        raise ValueError(f"裁剪图像失败: {e}")
